package com.baor.filter;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baor.config.JwtConfig;
import com.baor.dao.UserDao;
import com.baor.domain.LoginUser;
import com.baor.service.security.TokenService;
import com.baor.utils.AjaxResult;
import com.baor.utils.RedisUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Component
@EnableWebSecurity
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        StringBuilder headers = new StringBuilder();
        Enumeration<String> headerNames = request.getHeaders("Access-Control-Request-Headers");
        if(Objects.nonNull(headerNames)) {
            while (headerNames.hasMoreElements()) {
                if(StringUtils.isBlank(headers.toString())){
                    headers.append(headerNames.nextElement());
                }else{
                    headers.append(",").append(headerNames.nextElement());
                }
            }
        }
        response.setHeader("Access-Control-Allow-Headers", headers.toString());
        String uri = request.getRequestURI();
        response.setContentType("text/html;charset=utf-8");
        Map<String,Object> res = new HashMap<>();
        // 白名单
        if (uri.contains("/login")) {
            filterChain.doFilter(request, response);
            return;
        }
        // 获取token
        String authorization = request.getHeader("authorization");
        System.out.println("hls"+authorization);
        if (authorization == null || authorization.equals("")) {
            authorization = request.getParameter("authorization");
        }
        // 验证token
        if (authorization == null || authorization.equals("")) {
            res.put("code", "403");
            res.put("msg", "用户信息不存在");
            response.getWriter().print(res);
            return;
        }
        // 解析token
        Claims claims = tokenService.getBody(authorization);
        if (claims == null) {
            response.getWriter().println("authorization不存在或已过期...");
            return;
        }
        // 获取用户信息
        LoginUser loginUser = (LoginUser) this.redisUtil.getValue("loginUser:" + claims.getSubject());
        //验证状态
        String status = (String) this.redisUtil.getValue(loginUser.getUsername());
        if(!status.equals(authorization)){
            response.getWriter().append("请重新登录");
            return;
        }
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = null;
        try{
            usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginUser, loginUser.getPassword(), loginUser.getAuthorities());
        }catch (Exception e){
            System.out.println("error");
            response.getWriter().append("token不存在");
            return;
        }
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        filterChain.doFilter(request, response);
    }
}
